const fs = require('fs')
const path = require('path')
const pathResolve = (url) => {
  return path.resolve(__dirname, url)
}
const { baseUrl, translateResultUrl } = require('./config/index.js')
const outputUrl = `./outputData/`
const createDirsSync = (folderName, data, lang) => {
  let oldData = {}
  if (fs.existsSync(pathResolve(`${lang}-${folderName}.js`))) {
    oldData = JSON.parse(
      fs
        .readFileSync(pathResolve(`${lang}-${folderName}.js`))
        .toString()
        .replace('export default ', '')
    )
  }
  const pushData = data.reduce((current, item) => {
    return {
      ...current,
      [item.id]: item[lang.split('/').pop()],
    }
  }, {})

  const result = {
    ...oldData,
    ...pushData,
  }
  fs.writeFileSync(
    pathResolve(`${lang}-${folderName}.js`),
    `export default ${JSON.stringify(result)}`
  )
}

;(function () {
  const data = JSON.parse(
    fs.readFileSync(pathResolve(translateResultUrl)).toString()
  )
  
  let totalImport = ''
  const dealComponents = 'src/components/',
    dealView = 'src/views/'
  const dealFile = Object.keys(data).filter((obj) => {
    //只处理view下方的文件
    return obj.includes(dealComponents) || obj.includes(dealView)
  })

  dealFile.map((item, index) => {
    const commonPath = item.includes(dealComponents) ? dealComponents : dealView
    const fileExt = path.extname(item)
    const dealUrl = item.split(commonPath)[1].split('/')
    const folderName = dealUrl[0]
    //只输出一个文件
    createDirsSync(folderName, data[item], outputUrl + 'en')
    createDirsSync(folderName, data[item], outputUrl + 'zh-cn')
  })
  console.log('successful!')
})()
